import axios from 'axios'
import Vue from 'vue'

const TOKEN_KEY = "POINT-LINK-TOKEN"
const service = axios.create({
  baseURL: '/api',
  timeout: 5000
})
const router = Vue.$router
const toast = Vue.$toast

service.interceptors.request.use(config => {
  const token = localStorage.getItem(TOKEN_KEY)
  config.headers.common['Authorization'] = 'Bearer ' + token
  return config
})

service.interceptors.response.use(res => {
  const { data } = res
  if (data.code === -666) {
    toast.warning(data.message)
    .then(() => {
      // redirect({ path: '/login' })
      router.replace({
        path: '/login',
        querty: {redirect: router.currentRoute.fullPath}
      })
    }).catch(err => {
      console.log('confirm has error', err);
    })
  } 
  return Promise.resolve(data)
})

Vue.prototype.$http = service
export const http = service
